<template>
    <div class="demo-collapse">
        <el-card class="box-card">
            <template #header>
                会话列表（{{ tableInfo.conversationNum }}）
            </template>
            <div v-for="user in  handleConversation(tableInfo.conversationList)" class="flex-box"
                style="border-bottom: 1px solid #f6f6f6; margin: 10px;">
                <div class='flex-box'><el-avatar :src="user.avatar" :size="50"></el-avatar>
                    <el-button :type="onlineUsers?.includes(user.id) ? 'success' : 'danger'" link
                        @click="openConversation(user.id)">{{ user.nickname }}
                    </el-button>
                </div>
                <el-button type="primary" round @click="openConversation(user.id)">发送消息</el-button>
            </div>
        </el-card>
        <el-card>
            <template #header>
                人员名单
            </template>
            <el-collapse v-model="activeNames" @change="handleChange" accordion>
                <el-collapse-item :name="user.id" v-for="user in tableInfo.userList.filter(user => user.id !== id)">
                    <template #title>
                        <div class="flex-box">
                            <el-avatar :src="user.avatar" :size="40"></el-avatar> <b>{{ user.nickname }}</b>
                        </div>
                    </template>
                    <el-descriptions :column="3" border>
                        <el-descriptions-item label="用户名" label-align="right" align="center" label-class-name="my-label"
                            class-name="my-content" width="150px">{{ user.account }}</el-descriptions-item>
                        <el-descriptions-item label="电话" label-align="right" align="center">{{ user.phone
                        }}</el-descriptions-item>
                        <el-descriptions-item label="职业" label-align="right" align="center">{{
                            user.profession }}</el-descriptions-item>
                        <el-descriptions-item label="爱好" label-align="right" align="center">
                            <el-tag v-for="hobby in user.hobbies" :key="hobby.id" size="small" class="tag">{{ hobby.name
                            }}</el-tag>
                        </el-descriptions-item>
                        <el-descriptions-item label="地址" label-align="right" align="center">{{ user.address }}
                        </el-descriptions-item>
                        <el-descriptions-item label="邮箱地址" label-align="right" align="center">{{ user.email }}
                        </el-descriptions-item>
                        <el-descriptions-item label="个人简介" label-align="right" align="center">{{ user.introduction }}
                        </el-descriptions-item>
                        <el-descriptions-item label="粉丝数" label-align="right" align="center">{{ user.follower.length }}
                        </el-descriptions-item>
                        <el-descriptions-item label="关注数" label-align="right" align="center">{{ user.followings.length }}
                        </el-descriptions-item>
                        <el-descriptions-item label="操作" label-align="right" align="center">
                            <el-button type="warning" @click="openConversation(user.id)">私聊</el-button>
                        </el-descriptions-item>
                    </el-descriptions>
                </el-collapse-item>
            </el-collapse>
        </el-card>
    </div>


    <el-drawer v-model="drawer" size="60%" :show-close="false">
        <template #header>
            <strong style="text-align: center;  font-size: 20px;">
                <el-button link :type="onlineUsers?.includes(tableInfo.sessionDetail.receiverId) ? 'success' : 'danger'"
                    @click="innerDrawer = true">
                    {{ tableInfo.sessionDetail.nickname }} <span
                        v-if="!onlineUsers?.includes(tableInfo.sessionDetail.receiverId)">（未在线）</span> </el-button>
            </strong>
        </template>
        <div style="width: 100%; height:700px;overflow-y: auto; padding: 30px; border: 1px solid #e4e7ed;" ref="chatBoxRef">
            <div v-for="message in tableInfo.sessionDetail.messages">
                <div v-if="message.sender.id === id">
                    <div style="text-align: center;">{{ dayForMat(message.createdTime, 'YYYY-MM-DD hh:mm:ss') }}</div>
                    <div class="chat-text">
                        <div style="min-width: 40px; display: flex; flex-direction: column;transform: translateY(-20%);">
                            <span style="color:gray ">{{
                                message.sender.nickname }}</span>
                            <el-avatar :src="message.sender.avatar"></el-avatar>
                        </div>
                        <p style="margin-left: 10px; " class="content">
                            {{ message.content }}
                        </p>
                    </div>


                </div>
                <div class=" chat-text" style=" justify-content: end; " v-else>
                    <p style="margin-right: 10px;" class="content">{{ message.content }}
                    </p>
                    <div style="min-width: 40px; display: flex; flex-direction: column; transform: translateY(-20%);">
                        <span style="color:gray; ">{{ message.sender.nickname
                        }}</span>
                        <el-avatar :src="message.sender.avatar"></el-avatar>
                    </div>
                </div>
            </div>
        </div>
        <div style="display: flex;">
            <el-input v-model="tableInfo.content" ref="iptRef" @keyup.enter="sendMessage"></el-input> <el-button
                type="primary" round @click="sendMessage" :disabled="tableInfo.content === ''">发送</el-button>
        </div>
        <div>
            <el-drawer v-model="innerDrawer" :append-to-body="true">
                <template #header>
                    <strong>个人信息</strong>
                </template>
                <div style="display: flex;flex-direction: column; ">
                    <div style="display: flex; justify-content: center;">
                        <el-avatar :src="detailUserInfo?.avatar" :size="80"></el-avatar>
                        <div
                            style="display: flex;flex-direction: column; justify-content: space-around; margin-left: 20px;">
                            <strong>昵称：{{ detailUserInfo?.nickname }}</strong>
                            <span>账户：{{ detailUserInfo?.account }}</span>
                            <span>性别：{{ detailUserInfo?.gender }}</span>
                        </div>
                    </div>
                    <div class="detail-info-line">生日：{{ dayForMat(detailUserInfo?.birthday, 'YYYY-MM-DD') }}</div>
                    <div class="detail-info-line">电话：{{ detailUserInfo?.phone }}</div>
                    <div class="detail-info-line">邮箱：{{ detailUserInfo?.email }}</div>
                    <div class="detail-info-line">地址：{{ detailUserInfo?.address }}</div>
                    <div class="detail-info-line">简介：{{ detailUserInfo?.introduction }}</div>
                    <div class="detail-info-line">专业：{{ detailUserInfo?.profession }}</div>
                    <div class="detail-info-line">爱好：<el-tag class="tag" v-for="hobby in detailUserInfo?.hobbies"
                            type="success">{{ hobby.name }}</el-tag></div>
                    <div class="detail-info-line">注册时间：{{ dayForMat(detailUserInfo?.create_time, 'YYYY-MM-DD') }}</div>
                    <div class="detail-info-line">关注数：
                        <el-popover placement="top" width="180">
                            <template #reference>
                                <el-button type="primary" link>{{ detailUserInfo?.followings.length
                                }}</el-button>
                            </template>
                            <template #default>
                                <div v-if="detailUserInfo?.followings && !detailUserInfo.followings.length"
                                    style="text-align: center;">暂无关注</div>
                                <div class="demo-rich-conent" v-for="followings in detailUserInfo?.followings" v-else
                                    style="display: flex; gap: 14px;  align-items: center;">
                                    <el-avatar :size="40" :src="followings.avatar || logo" style="margin-bottom: 8px" />
                                    <span>昵称：{{ followings.nickname }}</span>
                                </div>
                            </template>
                        </el-popover>
                    </div>
                    <div class="detail-info-line">粉丝数：
                        <el-popover placement="top" width="180">
                            <template #reference>
                                <el-button type="primary" link>{{ detailUserInfo?.follower.length
                                }}</el-button>
                            </template>
                            <template #default>
                                <div v-if="detailUserInfo?.follower && !detailUserInfo.follower.length"
                                    style="text-align: center;">暂无粉丝</div>
                                <div class="demo-rich-conent" v-for="follower in detailUserInfo?.follower" v-else
                                    style="display: flex; gap: 14px;  align-items: center;">
                                    <el-avatar :size="40" :src="follower.avatar || logo" style="margin-bottom: 8px" />
                                    <span>昵称：{{ follower.nickname }}</span>
                                </div>
                            </template>
                        </el-popover>
                    </div>


                </div>
            </el-drawer>
        </div>
    </el-drawer>
</template>
  
<script lang="ts" setup name="conversation_list">
import { ref, onMounted, reactive, computed, inject, onBeforeUnmount, nextTick } from 'vue'
import { findAllCount, findMyConversation, createSession, followUp } from '@/api'
import { useUserInfoStore } from '@/stores';
import logo from '@/assets/images/logo.jpg'
import { ElMessage, ElMessageBox } from 'element-plus'
import { dayForMat } from '@/utils';

const chatBoxRef = ref<HTMLDivElement>()
const iptRef = ref<HTMLInputElement>()
const socket: any = inject('socket')
const userInfoStore = useUserInfoStore()
const { id, avatar, nickname, uuid } = userInfoStore.userInfo

const onlineUsers = ref<Array<number>>()
interface ConverSation {
    id: number,
    user1: number,
    user2: number,
    createdTime: string,
    messages: []
}
interface User {
    account: string,
    nickname: string,
    avatar: string,
    id: number,
    introduction: string,
    create_time: string,
    birthday: string,
    gender: '男' | '女'
    hobbies: [{ id: number, name: string }],
    phone: number,
    profession: string,
    email: string,
    address: string,
    follower: Array<any>,
    followings: Array<any>
}

interface tableInfo {
    userList: Array<User>,
    total: number,
    conversationList: Array<ConverSation>,
    conversationNum: number,
    sessionDetail: {
        avatar: string,
        createdTime: string,
        id: number,
        receiverId: number,
        nickname: string,
        messages: Array<{
            content: string,
            createdTime: string,
            read: boolean,
            sender: {
                avatar: string, id: number, nickname: string
            },
            receiver: any
        }>
    },
    content: string
}

const tableInfo = reactive<tableInfo>({
    userList: [],
    total: 0,
    conversationList: [],
    conversationNum: 0,
    sessionDetail: {
        avatar: '',
        receiverId: 0,
        createdTime: '',
        id: 0,
        messages: [],
        nickname: ''
    },
    content: ''
})


onMounted(async () => {
    socket.on('receiveMessage', (data: any) => {
        tableInfo.sessionDetail.messages.push(data)
    })
    //及时更新用户下线上线情况
    socket.on('onlineUserIds', (data: Array<number>) => {
        onlineUsers.value = data
        console.log(data);
    })
    //获取用户在线状态
    socket.emit('onlineUsers')
    //获取用户最新在线状态
    socket.on('getOnlineUsers', (data: Array<number>) => {
        onlineUsers.value = data
    })
    try {
        initMyUserList()
        initMyConverSation()
    } catch (error) { }
})

const initMyUserList = async () => {
    const res = await findAllCount()
    tableInfo.userList = res.data.data
    tableInfo.total = res.data.total
}

const initMyConverSation = async () => {
    try {
        const converSationList = await findMyConversation(id)
        tableInfo.conversationList = converSationList.data.data[0]
        tableInfo.conversationNum = converSationList.data.data[1]
    } catch (error) { }
}
const openConversation = async (otherId: number) => {
    drawer.value = true
    nextTick(async () => {
        setTimeout(() => {
            chatBoxRef.value && (chatBoxRef.value.scrollTop = chatBoxRef.value.scrollHeight)
            iptRef.value && iptRef.value.focus()
        }, 300)
    })
    const data = { senderId: id, receiverId: otherId }
    const res = await createSession(data)
    tableInfo.sessionDetail = handleConversation(res.data.data)
    if (res.data.code === 302) {
        //说明存在 就没必要更新会话框数量
    } else {
        initMyConverSation() 
    }
}
//点击发送请求 参考之前的项目  
const sendMessage = async () => {
    const messageDto = {
        sessionDetail: {
            sender: {
                id,
                avatar,
                nickname
            },
            receiver: {
                id: tableInfo.sessionDetail.receiverId,
            }
        },
        conversationId: tableInfo.sessionDetail.id,
        content: tableInfo.content
    }
    socket.emit('sendMessage', messageDto)
    tableInfo.content = ''
    iptRef.value?.focus()
}



//取消之前的监听事件
onBeforeUnmount(() => {
    socket.off('receiveMessage')
    socket.off('onlineUserIds')
    socket.off('getOnlineUsers')
})

//处理会话的格式
const handleConversation = (converSationList: Array<ConverSation> | ConverSation): any => {
    if (Array.isArray(converSationList)) {
        return converSationList.map(item => {
            if (id === item.user1) {
                const { avatar, nickname, id: id2 } = tableInfo.userList.filter((user: User) => user.id === item.user2)[0]
                return { avatar, nickname, id: id2 }
            }
            else {
                const { avatar, nickname, id: id2 } = tableInfo.userList.filter((user: User) => user.id === item.user1)[0]
                return { avatar, nickname, id: id2 }
            }
        })
    } else {
        if (id === converSationList.user1) {
            const { avatar, nickname } = tableInfo.userList.filter((user: User) => user.id === converSationList.user2)[0]
            return { avatar, nickname, id: converSationList.id, receiverId: converSationList.user2, createdTime: converSationList.createdTime, messages: converSationList.messages }
        }
        else {
            const { avatar, nickname, id: id3 } = tableInfo.userList.filter((user: User) => user.id === converSationList.user1)[0]
            return { avatar, nickname, id: converSationList.id, receiverId: converSationList.user1, createdTime: converSationList.createdTime, messages: converSationList.messages }
        }
    }

}

//接收方详细信息
const detailUserInfo = computed(() => {
    return tableInfo.userList.find(item => item.id === tableInfo.sessionDetail.receiverId)
})

const handleFollow = async (follow_uuid: string) => {
    const data = { uuid, follow_uuid }
    const res = await followUp(data)
    if (res.data.code == 200) {
        ElMessage({
            message: res.data.msg,
            type: 'success'
        })
        initMyUserList()
    } else {
        ElMessage({
            type: 'error',
            message: res.data.msg
        })
    }
}

const activeNames = ref(['1'])
const handleChange = (val: string[]) => {
    // console.log(val)
}



//二层抽屉
const drawer = ref(false)
const innerDrawer = ref(false)

// const handleClose = (done: () => void) => {
//     ElMessageBox.confirm('You still have unsaved data, proceed?')
//         .then(() => {
//             done()
//         })
//         .catch(() => {
//             // catch error
//         })
// }
</script>

<style lang="scss" scoped>
.my-label {
    background: var(--el-color-success-light-9);
}

.my-content {
    background: var(--el-color-danger-light-9);
}

.tag {
    margin: 0 5px;
}

.flex-box {
    display: flex;
    align-items: center;
    justify-content: space-between;
}

.box-card {
    margin-bottom: 20px;
    // padding: 20px;
}

.chat-text {
    width: 100%;
    display: flex;
    align-items: center;
    line-height: 30px;

    .contnet {
        padding: 20px 0;
        word-wrap: break-word;
        word-break: break-all;
    }
}

.detail-info-line {
    padding: 15px 0;
}
</style>
  